package com.zefor.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zefor.pojo.CorralPojo;
import com.zefor.pojo.EquipmentPojo;
import com.zefor.pojo.FarmPojo;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import org.apache.pulsar.client.api.*;

import java.util.*;

public class SycFarmInfo extends AbstractTask {

    private static ObjectMapper mapper = new ObjectMapper();

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        ArrayList<FarmPojo> result = new ArrayList<>();
        DynamicObject[] managers = BusinessDataServiceHelper.load("n716_dev_manager",
                "n716_basedatafield , n716_basedatafield1 , n716_basedatafield2", null);
        for (DynamicObject manager : managers) {
            // 厂房信息
            DynamicObject farm = QueryServiceHelper.queryOne("n716_farm", "*",
                    new QFilter("id", QCP.equals, manager.get("n716_basedatafield2_id")).toArray());
            // 栏舍信息
            DynamicObject corral = QueryServiceHelper.queryOne("n716_corral", "*",
                    new QFilter("id", QCP.equals, manager.get("n716_basedatafield1_id")).toArray());
            // 环控设备信息
            DynamicObject equipment = QueryServiceHelper.queryOne("n716_equipmentlink", "*",
                    new QFilter("id", QCP.equals, manager.get("n716_basedatafield_id")).toArray());

            if (result.isEmpty()) {
                result.add(new FarmPojo((Long) manager.get("n716_basedatafield2_id"), (String) farm.get("name"),
                        new ArrayList<CorralPojo>() {
                            {
                                add(new CorralPojo((Long) manager.get("n716_basedatafield1_id"),
                                        (String) corral.get("name"), new ArrayList<EquipmentPojo>() {
                                    {
                                        add(new EquipmentPojo((Long) manager.get("n716_basedatafield_id"),
                                                (String) equipment.get("name"),
                                                (Date) equipment.get("createtime")));
                                    }
                                }, (Date) corral.get("createTime")));
                            }
                        }, (Date) farm.get("createtime")));
            } else {
                for (int i = 0; i < result.size(); i++) {
                    // 如果养殖场存在,那么添加栏舍
                    if (result.get(i).getName().equals(farm.get("name"))) {
                        List<CorralPojo> corrals = result.get(i).getCorrals();
                        for (int j = 0; j < corrals.size(); j++) {
                            // 判断栏舍是否存在,如果不存在那么添加
                            CorralPojo corralPojo = corrals.get(j);
                            if (corralPojo.getName().equals(corral.get("name"))) {
                                // 添加环控设备信息
                                for (int k = 0; k < corralPojo.getEquipments().size(); k++) {
                                    if (corralPojo.getEquipments().get(k).getName().equals(equipment.get("name"))) {
                                        continue;
                                    }
                                    if (k == corralPojo.getEquipments().size() - 1) {
                                        result.get(i).getCorrals().get(j).getEquipments()
                                                .add(new EquipmentPojo((Long) manager.get("n716_basedatafield_id"),
                                                        (String) equipment.get("name"),
                                                        (Date) equipment.get("createtime")));
                                    }
                                }
                                break;
                            }
                            if (j == corrals.size() - 1) {
                                result.get(i).getCorrals()
                                        .add(new CorralPojo((Long) manager.get("n716_basedatafield1_id"),
                                                (String) corral.get("name"), new ArrayList<EquipmentPojo>() {
                                            {
                                                add(new EquipmentPojo(
                                                        (Long) manager.get("n716_basedatafield_id"),
                                                        (String) equipment.get("name"),
                                                        (Date) equipment.get("createtime")));
                                            }
                                        }, (Date) corral.get("createtime")));
                            }
                        }
                        break;
                    }
                    // 如果不存在那么添加养殖场
                    if (i == result.size() - 1) {
                        result.add(new FarmPojo((Long) manager.get("n716_basedatafield2_id"), (String) farm.get("name"),
                                new ArrayList<CorralPojo>() {
                                    {
                                        add(new CorralPojo((Long) manager.get("n716_basedatafield1_id"),
                                                (String) corral.get("name"), new ArrayList<EquipmentPojo>() {
                                            {
                                                add(new EquipmentPojo(
                                                        (Long) manager.get("n716_basedatafield_id"),
                                                        (String) equipment.get("name"),
                                                        (Date) equipment.get("createtime")));
                                            }
                                        }, (Date) corral.get("createTime")));
                                    }
                                }, (Date) farm.get("createtime")));
                    }
                }
            }
        }
        try {
            // 包装一个时间戳
            HashMap<String, String> resEntity = new HashMap<>();
            resEntity.put("createTime", String.valueOf(System.currentTimeMillis()));
            resEntity.put("data", mapper.writeValueAsString(result));
            PulsarClient build = PulsarClient.builder()
                    .serviceUrl("pulsar://123.114.60.34:16339")
                    .authentication(AuthenticationFactory.token(
                            "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNjg0NzMzNjA4In0.Kh4Dlb5LibWJIa-hrFF5Y1Rl-fiZapqhp8YAoEPV2nA"))
                    .build();
            Producer<String> producer = build.newProducer(Schema.STRING)
                    .topic("persistent://Y1wuy9mvcD/-CgTvY-Xh/SycFarmInfo")
                    .create();

            System.out.println(mapper.writeValueAsString(resEntity));
            // 发送消息
            producer.newMessage()
                    .value(mapper.writeValueAsString(resEntity))
                    .send();
            producer.close();
            build.close();
            build.shutdown();
        } catch (JsonProcessingException | PulsarClientException e) {
            throw new RuntimeException(e);
        }
    }
}
